package org.jeecg.zhenxuan.CommonUtils;

import java.util.*;

public class MapComparator {
	/**
	 * 使用 Map按key进行排序
	 *
	 * @param map
	 * @return
	 */
	public static Map<String, String> SortMapByKey(Map<String, String> map) {
		if (map == null || map.isEmpty()) {
			return null;
		}
		Map<String, String> sortMap = new TreeMap<String, String>(new MapKeyComparator());
		sortMap.putAll(map);
		return sortMap;
	}

	/**
	 * 使用 Map按value进行排序
	 *
	 * @param map
	 * @return
	 */
	public static Map<String, String> SortMapByValue(Map<String, String> oriMap) {
		if (oriMap == null || oriMap.isEmpty()) {
			return null;
		}
		Map<String, String> sortedMap = new LinkedHashMap<String, String>();
		List<Map.Entry<String, String>> entryList = new ArrayList<Map.Entry<String, String>>(oriMap.entrySet());
		Collections.sort(entryList, new MapValueComparator());

		Iterator<Map.Entry<String, String>> iter = entryList.iterator();
		Map.Entry<String, String> tmpEntry = null;
		while (iter.hasNext()) {
			tmpEntry = iter.next();
			sortedMap.put(tmpEntry.getKey(), tmpEntry.getValue());
		}
		return sortedMap;
	}

	/**
	 * 将得到Map对象按照key=value&key1=value1...的格式返回
	 *
	 * @param resultMap
	 * @return
	 */
	public static String getMapToString(Map<String, String> resultMap) {
		String result = "";
		for (Map.Entry<String, String> entry : resultMap.entrySet()) {
			result += entry.getKey() + "=" + entry.getValue() + "&";
		}
		if (result != null && !"".equals(result)) {
			result = result.substring(0, result.length() - 1);
		}

		return result;
	}

	static class MapKeyComparator implements Comparator<Object>{

		@Override
		public int compare(Object str1, Object str2) {

			return str1.toString().compareTo(str2.toString());
		}
	}


}

class MapValueComparator implements Comparator<Map.Entry<String, String>> {
	@Override
	public int compare(Map.Entry<String, String> me1, Map.Entry<String, String> me2) {

		return me1.getValue().compareTo(me2.getValue());
	}
}
